# -*- encoding=utf8 -*-

__author__ = "code哥"
import random
import sys
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco

dev = False

if dev:
    poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
    from airtest.cli.parser import cli_setup

    if not cli_setup():
        auto_setup(__file__, logdir=None, devices=[
            "Android://127.0.0.1:5037/M960BDPT226TA?cap_method=JAVACAP&&ori_method=ADBORI",
        ])
else:
    import timeout_decorator

    # M960BDPT226TA WIFI 10.0.0.26 48003
    argv1 = str(sys.argv[1])
    argv2 = str(sys.argv[2])
    argv3 = str(sys.argv[3])
    argv4 = str(sys.argv[4])

    if argv2 == 'USB':
        conn_info = 'Android://127.0.0.1:5037/{uuid}?cap_method=JAVACAP&&ori_method=ADBORI'.format(
            uuid=argv1)
        device = connect_device(conn_info)
    else:
        # WIFI模式
        conn_info = 'Android://127.0.0.1:5037/{clientIp}:{port}'.format(
            clientIp=argv3,
            port=argv4)
        print(conn_info)
        device = connect_device(conn_info)

    poco = AndroidUiautomationPoco(device, use_airtest_input=True, screenshot_each_action=False)

    logdir = "{path}/static/source_img/{fileName}/{devices}".format(
        path=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
        fileName=str(os.path.abspath(__file__).split('/')[-1]).split('.py')[0],
        devices=argv1)
    if not os.path.exists(logdir):
        os.makedirs(logdir)
    auto_setup(__file__,
               logdir=logdir,
               devices=[conn_info, ],
               project_root="{root}".format(root=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))


def start():
    if not dev:
        set_logdir(logdir)
        # set_current(str(sys.argv[1]))
    # 退到桌面
    home()
    stop_app('com.yuncheapp.android.pearl')
    sleep(1)
    start_app('com.yuncheapp.android.pearl')
    start_home()


def start_home():
    sleep(15)
    coin_get = poco(type="android.widget.TextView", name="com.yuncheapp.android.pearl:id/coin_get")
    if coin_get.exists():
        coin_get.click()
    recycler_view = poco(type="android.support.v7.widget.RecyclerView",
                         name="com.yuncheapp.android.pearl:id/recycler_view")
    recycler_view.swipe([0, 0.5])
    sleep(2)
    tab_icon_container_list = poco(type="android.widget.LinearLayout",
                                   name="com.yuncheapp.android.pearl:id/home_page_tab_bar").children()
    if tab_icon_container_list.exists():
        select = random.randint(1, 2)
        if select == 1:
            tab_icon_container_list[3].click()
            sleep(1)
            grid_item_list = poco(type="android.widget.RelativeLayout",
                                  name="com.yuncheapp.android.pearl:id/feed_grid_item_container")
            if len(grid_item_list) > 0:
                for item in grid_item_list:
                    item.click()
                    break
                while True:
                    loop_body()
        elif select == 2:
            tab_icon_container_list[0].click()
            sleep(1)
            id_root_list = poco(type="android.widget.LinearLayout",
                                name="com.yuncheapp.android.pearl:id/root")
            sleep(1)
            if id_root_list is not None and len(id_root_list) > 0:
                for item in id_root_list:
                    item.click()
                    sleep(1)
                    break
                while True:
                    loop_body2()


@timeout_decorator.timeout(60)
def loop_body():
    print('loop_body......')
    horizontal_view_pager = poco(type="android.support.v4.view.ViewPager",
                                 name="com.yuncheapp.android.pearl:id/horizontal_view_pager")
    sleep(0.5)
    timer_anchor = poco(type="android.view.View", name="com.yuncheapp.android.pearl:id/timer_anchor")
    if not timer_anchor.exists():
        horizontal_view_pager.swipe([0, -0.9])
    else:
        if exists(Template(r"img/tpl_kuaikandian_za_btn.png", record_pos=(0.392, -0.075), resolution=(1440, 2560))):
            timer_anchor.click()
            sleep(2)
            dialog_close = poco(type="android.widget.ImageView", name="com.yuncheapp.android.pearl:id/dialog_close")
            if dialog_close.exists():
                dialog_close.click()

        sleep(5 + random.randint(1, 3))
        horizontal_view_pager.swipe([0, -0.9])


@timeout_decorator.timeout(120)
def loop_body2():
    print('loop_body2......')
    if exists(Template(r"img/tpl_kuaikandian_article_za_btn.png", record_pos=(0.392, 0.678), resolution=(1440, 2560))):
        touch(Template(r"img/tpl_kuaikandian_article_za_btn.png", record_pos=(0.392, 0.678), resolution=(1440, 2560)))
        sleep(2)
    dialog_close = poco(type="android.widget.ImageView", name="com.yuncheapp.android.pearl:id/dialog_close")
    if dialog_close.exists():
        dialog_close.click()
        sleep(0.5)
    detail_scrollview = poco(type="android.view.ViewGroup", name="com.yuncheapp.android.pearl:id/detail_scrollview")
    if detail_scrollview.exists():
        detail_scrollview.swipe([0, -0.7], duration=1.5)
        sleep(1)
    id_root_list = poco(type="android.support.v7.widget.RecyclerView",
                        name="com.yuncheapp.android.pearl:id/rv").children()
    if id_root_list.exists():
        for item in id_root_list:
            if item.attr("name") == "com.yuncheapp.android.pearl:id/root":
                item.click()
                break


def main():
    try:
        start()
    except Exception as e:
        print(e)


if __name__ == '__main__':
    main()
